package com.bestcem.xm.user.service.impl;

import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ValidationErrorCodeEnum;
import com.bestcem.xm.user.constant.UserCacheKeyConstant;
import com.bestcem.xm.user.controller.param.CreateBookingParam;
import com.bestcem.xm.user.dao.WhitepaperSubscribeDao;
import com.bestcem.xm.user.entity.pojo.WhitepaperSubscribeDO;
import com.bestcem.xm.user.grpc.client.IndustryGrpcService;
import com.bestcem.xm.user.grpc.client.dto.IndustryDTO;
import com.bestcem.xm.user.service.WhitepaperSubscribeService;
import com.bestcem.xm.user.service.dto.user.NotifyApplicationByEmailDTO;
import com.bestcem.xm.user.service.third.PhoneService;
import com.bestcem.xm.user.util.business.UserCacheUtil;
import com.bestcem.xm.user.util.business.UserUtil;
import com.bestcem.xm.user.util.convert.WhitepaperSubscribeConvert;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/14 22:10
 */
@Slf4j
@Service
public class WhitepaperSubscribeServiceImpl implements WhitepaperSubscribeService {
    @Resource
    private PhoneService phoneService;
    @Resource
    private IndustryGrpcService userIndustryGrpcService;
    @Resource
    private WhitepaperSubscribeDao whitepaperSubscribeDao;
    @Resource
    private WhitepaperSubscribeConvert convert;
    @Autowired
    private UserCacheUtil userCacheUtil;
    @Resource
    private UserUtil userUtil;
    @Value("${app.user.whitepaperSubscribeMail:}")
    private String mail;

    @Override
    public ServiceResult<String> createBooking(CreateBookingParam param) {
        // 验证短信验证码
        String vcodeKey = String.format(UserCacheKeyConstant.USER_WHITEPAPER_SUBSCRIBE_VCODE, param.getPhone());
        String cacheVcode = userCacheUtil.get(vcodeKey);
        if (StringUtils.isEmpty(cacheVcode) || !cacheVcode.equalsIgnoreCase(param.getVcode())) {
            return ServiceResult.fail(ValidationErrorCodeEnum.VCODE_ERROR, "短信验证码错误");
        }
        WhitepaperSubscribeDO whitepaperSubscribeDO = whitepaperSubscribeDao.getOneByPhone(param.getPhone());
        if (Objects.nonNull(whitepaperSubscribeDO)) {
            return ServiceResult.success(null, "user already exists");
        }
        whitepaperSubscribeDO = convert.param2Do(param);
        String location = phoneService.getPhoneLocation(param.getPhone());
        whitepaperSubscribeDO.setLocation(location);

        IndustryDTO industryDTO = userIndustryGrpcService.getByCode(param.getIndustry());
        String industryName = Optional.of(industryDTO).map(IndustryDTO::getName).orElse("");

        String district = Optional.of(param.getDistrict()).orElse("East");
        IndustryDTO industryInfo = userIndustryGrpcService.getByCodeAndDistrict(param.getIndustry(), district);
        List<String> emailList = Optional.of(industryInfo).map(IndustryDTO::getSalesEmails).orElse(new ArrayList<>());
        if (StringUtils.isNotEmpty(mail)) {
            emailList.add(mail);
        }
        boolean isInner = userUtil.checkUserIsInner(param.getPhone(), param.getEmail(), null);
        if (!isInner) {
            NotifyApplicationByEmailDTO emailDTO = new NotifyApplicationByEmailDTO();
            emailDTO.setToEmail(emailList);
            emailDTO.setSubject("白皮书下载");
            emailDTO.setContent("姓名：" + param.getName()
                    + "\\n手机号：" + param.getPhone()
                    + "\\n企业名称：" + param.getOrgName()
                    + "\\n邮箱：" + Optional.of(param.getEmail()).orElse("未填")
                    + "\\n行业：" + industryName
                    + "\\n号码归属地:" + location + "\\n");
            userUtil.notifyApplicationByEmail(emailDTO);
        }
        String id = whitepaperSubscribeDao.insertSelective(whitepaperSubscribeDO);
        return ServiceResult.success(id);
    }
}

